﻿using anydata.Wrokers;
using NsqSharp;
using System.Text;

namespace anydata.Models
{
    public class MessageHandler : IHandler
    {
        private readonly ILogger _logger;
        public event Action<string> OnMessgae;
        public MessageHandler(ILogger logger)
        {
            _logger = logger;
        }

        /// <summary>Handles a message.</summary>
        public void HandleMessage(IMessage message)
        {
            string msg = Encoding.UTF8.GetString(message.Body);
            if (msg != "heartbeat")
            {
                OnMessgae?.Invoke(msg);
            }
        }

        /// <summary>
        /// Called when a message has exceeded the specified <see cref="Config.MaxAttempts"/>.
        /// </summary>
        /// <param name="message">The failed message.</param>
        public void LogFailedMessage(IMessage message)
        {
            string msg = Encoding.UTF8.GetString(message.Body);
            _logger.LogError(msg);
        }
    }
}
